package socket;

import java.io.*;
import java.net.Socket;//Socket套接字，封装了tcp协议的通讯细节，使用它可以与远端服务建立TCP连接
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
//

public class Cient {
    private Socket socket;
    /*
    初始化客户端
     */
    public Cient(){
        try {
            System.out.println("正在于服务端建立连接......");
            socket = new Socket("localhost",8088);
                System.out.println("与服务端建立连接！");
            start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /*
    客户端开始工作的方法
     */
    public void start(){
        Scanner scanner = new Scanner(System.in);

            try {
                Thread t1 = new Thread(){
                    public void run() {
                        while (true) {
                            String s;
                            try {
                                InputStream is = socket.getInputStream();
                                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                                BufferedReader br = new BufferedReader(isr);
                                if ((s = br.readLine()) != null) {
                                    System.out.println(s);
                                }

                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                };
                t1.setDaemon(true);
                t1.start();
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                PrintWriter pw = new PrintWriter(bw,true);

                while (true) {
//                    System.out.println("请输入");
                    String s = scanner.nextLine();
                    if ("exit".equalsIgnoreCase(s)){
                        break;
                    }
                    pw.println(s);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }

    public static void main(String[] args) {
        new Cient();
    }
}
